import _ from 'underscore';
import Mn from 'backbone.marionette';
import Radio from 'backbone.radio';
import ConfigBus from '../../base/components/ConfigBus.js';

import ExpenseTypeCollection from '../models/ExpenseTypeCollection.js';

/**
 * Specialized config bus responder for Expense Types
 *
 * Answers side-to-side with ConfigBus on same 'config' radio channel.
 */
const ExpenseTypeServiceClass = Mn.Object.extend({
    channelName: 'config',
    radioRequests: {
        'get:typeOptions': 'getTypeOptions',
        'get:ExpenseType': 'get',
    },
    setFormConfig(form_config) {
        let allExpenseTypes = _.flatten([
            form_config.options.expensekm_types,
            form_config.options.expense_types,
            form_config.options.expensetel_types,
            form_config.options.purchase_types,
        ]);
        this.expenseTypes = {
            km: new ExpenseTypeCollection(form_config.options.expensekm_types),
            expense: new ExpenseTypeCollection(form_config.options.expense_types),
            purchase: new ExpenseTypeCollection(form_config.options.purchase_types),
            tel: new ExpenseTypeCollection(form_config.options.expensetel_types),
            all: new ExpenseTypeCollection(allExpenseTypes),
        };
    },
    getTypeOptions(family) {
        /**
         * Provides objects with objects suitable for <option> initialization
         *
         * @param familly: one of 'tel', 'expense', 'purchase', or 'km'.
         * @return list of {id: …, label: …, category: 'all'|'0'|'1'}
         */
        if (!this.expenseTypes[family]) {
            throw new Error(`Unknown expense type family: ${family}`);
        }
        return this.expenseTypes[family].models.map(
            x => ({
                id: x.id,
                label: x.get('label'),
                category: x.get('category'),
            }));
    },
    get(id) {
        return this.expenseTypes.all.get(id);
    },
    setup(form_config_url) {
        console.log("ExpenseTypeServiceClass.setup");
    },
    start() {
        console.log("ExpenseTypeServiceClass.start");
        this.setFormConfig(ConfigBus.form_config);
        let result = $.Deferred();
        result.resolve(ConfigBus.form_config, null, null);
        return result;
    },
});

const ExpenseTypeService = new ExpenseTypeServiceClass();
export default ExpenseTypeService;